<template>
  <d2-container>
    <template slot="header">
      <div style="display: flex;width: 100%">
        <div class="search" style="display: flex;justify-content: space-around;width: 50%;">
          <div class="search_box" style="display: flex;justify-content: space-around;width: 100%">
            <div class="search_uid" style="width: 25%">
              <el-input v-model="user.uid" placeholder="用户ID" ></el-input>
            </div>
            <div class="search_telephone" style="width: 25%">
              <el-input v-model="user.telphone" placeholder="请输入手机号码"></el-input>
            </div>
            <div class="search_realname" style="width: 25%">
              <el-input v-model="user.real_name" placeholder="请输入用户真实姓名"></el-input>
            </div>
          </div>
          <div class="search_button" style="width: 20%">
            <el-button type="primary" style="width: 100%" @click="search_info">点击查询</el-button>
          </div>
        </div>
        <div>
          <el-button type="primary" style="margin-left: 20px" @click="addUser">点击添加数据</el-button>
        </div>
        <div>
          <el-button type="primary" style="margin-left: 20px" @click="Refresh">点击刷新页面</el-button>
        </div>
      </div>
    </template>
    <template>
      <el-table
              :data="tableData"
              stripe
              style="width: 100%">
        <el-table-column
                prop="uid"
                label="用户ID"
                align = "center">
        </el-table-column>
        <el-table-column
                prop="username"
                label="姓名"
                align = "center">
        </el-table-column>

        <el-table-column
                prop="telphone"
                label="用户电话号码"
                align = "center">
        </el-table-column>
        <el-table-column
                prop="real_name"
                label="真实姓名"
                align = "center">
        </el-table-column>
        <el-table-column
                prop="create_time"
                label="注册时间"
                align = "center">
          <template slot-scope="scope">
            {{ new Date(parseInt(scope.row.create_time))|moment('YYYY-MM-DD hh:mm') }}
          </template>
        </el-table-column>
        <el-table-column
                prop="idcard"
                label="身份证号码"
                align = "center">
        </el-table-column>
        <el-table-column
                prop="sex"
                label="性别"
                align = "center">
          <template slot-scope = "scope">
          {{ scope.row.sex == 1 ? '男':'女' }}
        </template>
        </el-table-column>
        <el-table-column
                prop="address"
                label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editUser(scope.row.uid)">编辑</el-button>
            <el-button @click="deleteUser(scope.row.uid)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </template>



    <!--添加用户 dialog-->
    <el-dialog
            title="添加用户数据"
            :visible.sync="addUserdialog"
            width="350px"
    >
      <el-form ref="form" :model="user" label-width="80px">
        <el-form-item label="用户名" style="width: 300px">
          <el-input v-model="adduser.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" style="width: 300px">
          <el-input v-model="adduser.telphone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" style="width: 300px">
          <el-input v-model="adduser.real_name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" style="width: 300px">
          <el-input v-model="adduser.idcard"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="adduser.sex">
            <el-radio label="1" >男</el-radio>
            <el-radio label="0" >女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmAdd">确认添加</el-button>
          <el-button @click="addUserdialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--修改用户数据-->
    <el-dialog
            title="修改用户数据"
            :visible.sync="editUserdialog"
            width="400px"
    >
      <el-form ref="form" :model="edituser" label-width="80px">
        <el-form-item label="用户名" style="width: 300px">
          <el-input v-model="edituser.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" style="width: 300px">
          <el-input v-model="edituser.telphone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" style="width: 300px">
          <el-input v-model="edituser.real_name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" style="width: 300px">
          <el-input v-model="edituser.idcard"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group  v-model="edituser.sex" >
            <el-radio :label="1" >男</el-radio>
            <el-radio :label="0" >女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmEdit" style="margin-left: 0">确认修改</el-button>
          <el-button @click="editUserdialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--删除用户-->
    <el-dialog
            title="警告！"
            :visible.sync="dialogVisible"
            width="30%"
    >
      <span>数据删除后将无法恢复，是否确认删除？</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="danger" @click="confirmDel">确 定</el-button>
  </span>
    </el-dialog>

    <template slot="footer">
      <template>
        <div class="block">
          <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[5, 10, 20, 30, 40]"
                  :page-size="10"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
          </el-pagination>
        </div>
      </template>
    </template>
  </d2-container>
</template>

<script>
  export default {
    name: 'userList',
    data () {
      return {
        dialogVisible: false,
        addUserdialog: false,
        editUserdialog: false,
        delUserId: '',
        editUserId: '',
        user: {
          userType: '',
          username: '',
          telphone: '',
          real_name: '',
          sex: '',
          idcard: '',
        },
        adduser: {
          userType: '',
          username: '',
          telphone: '',
          real_name: '',
          idcard: '',
          sex: ''
        },
        edituser: {
          userType: '',
          username: '',
          telphone: '',
          real_name: '',
          idcard: '',
          sex: ''
        },
        tableData: [],
        currentPage:1,
        limit:30,
        total:50
      }
    },
    async created () {
      this.getList()
    },
    methods: {
      handleSizeChange (val) {
        this.limit = val;
        this.getList();
      },
      handleCurrentChange (val) {
        this.currentPage  = val;
        this.getList();
      },
      async getList () {
       try {
         const res = await this.$api.post('/user/userlist',{limit:this.limit,page:this.currentPage});
         this.total = res.data.data.count;
         this.tableData = res.data.data.rows;
       } catch (e) {
         this.$message.error('服务器异常，获取数据失败！');
       }
      },
      async search_info() {
        try {
          let not_null = [];
          for (let v in this.user) {
            if (this.user[v] === '') {
              not_null.push(v);
            }
          }
          if (not_null.length > 0) {
            const res = await this.$api.post('/user/userlist',{
              uid: this.user.uid,
              telphone: this.user.telphone,
              real_name: this.user.real_name,
              limit:this.limit,
              page:this.currentPage
            });
            if(res.data.state == 1){
              for (let v in this.user)  {
                this.user[v] = '';
              }
              this.tableData = res.data.data.rows;
            }else {
              this.$message.error('出现未知错误！');
              this.getList();
            }
          } else {
            this.$message.error('请输入至少一个字段进行查询！')
          }
        } catch (e) {
          this.$message.error('服务器异常，获取数据失败！');
        }
      },
      addUser() {
        // 清空表单
        for(let v in this.user) {
          this.user[v] = '';
        }
        //显示弹窗
        this.addUserdialog = true;
      },
      async confirmAdd() {
        try {
          let testPhone = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\d{8}$/;
          let testName = /^[\u4E00-\u9FA5]{1,4}$/;
          let testId = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/;

          if(!testPhone.test(this.adduser.telphone)){
            this.$message.error('请填写中国人的手机号码！'); // 手机号过滤
            return false;
          }else if (!testName.test(this.adduser.real_name)) {
            this.$message.error('请输入中国人的姓名！'); // 姓名过滤
            return false;
          } else if (!testId.test(this.adduser.idcard)) {
            this.$message.error('请输入中国人的身份证号！'); //身份证过滤
            return false;
          }else if (this.adduser.sex === '') {
            this.$message.error('请选择性别 (￣ー￣)'); //选择性别
          } else {
            const res = await this.$api.post('/user/adduser', this.adduser);
            if (res.data.state == 1) {
              this.$message({ message: '添加成功！', type: 'success' });
              this.addUserdialog = false;
              this.getList();
            } else {
              this.$message.error('添加失败！');
              this.getList();
            }
          }
        } catch (e) {
          this.$message.error('服务器异常，获取数据失败！');
        }

      },
      async editUser(uid) {
        try {
          this.editUserId = uid;
          const res = await this.$api.post('/user/getuserbyId',{uid: this.editUserId});
          const {
            userType,
            username,
            telphone,
            real_name,
            sex,
            idcard } = res.data.data;
          this.edituser =  {
            userType,
            username,
            telphone,
            real_name,
            sex,
            idcard
          };
          this.editUserdialog = true;
        } catch (e) {
          this.$message.error('服务器异常，获取数据失败！');
        }
      },
      async confirmEdit() {
        try {
          let is_null = [];
          for (let v in this.edituser) {
            if (this.edituser[v] === '') {
              is_null.push(v);
            }
          }
          if (is_null.length === 0) {
            this.edituser.uid = this.editUserId;
            const res = await this.$api.post('/user/updatauser', this.edituser);
            if(res.data.state == 1) {
              this.$message({ message: '修改成功！', type: 'success' });
              this.editUserdialog = false;
              this.getList();
            }else {
              this.$message.error('修改失败！');
              this.getList();
            }
          } else {
            this.$message.error('不能有数据为空！')
          }
        } catch (e) {
          this.$message.error('服务器异常，获取数据失败！');
        }
      },
      deleteUser(uid) {
        this.dialogVisible = true;
        this.delUserId = uid;
      },
      async confirmDel() {
        try {
          const res = await this.$api.post('/user/deluser',{uid: this.delUserId});
          if(res.data.state == '1'){
            this.$message({ message: '删除成功！', type: 'success' });
            this.dialogVisible = false;
            this.getList();
          } else {
            this.$message.error('删除失败！');
            this.getList();
          }
        } catch (e) {
          this.$message.error('服务器异常，获取数据失败！');
        }
      },
      Refresh() {
        window.location.reload();
      }
    }
  }
</script>
<style>
  #app > div > div.d2-layout-header-aside-content > div.d2-theme-container > div.d2-theme-container-main > div:nth-child(2) > div.d2-theme-container-main-body > div > div > div.d2-container-full__body > div:nth-child(2) > div > div.el-dialog__body{
    padding: 20px 20px 10px;
  }
  .el-form-item:last-child>div{
    margin-left: 70px !important;
  }
</style>
